#!/bin/sh

# 白名单管理脚本

# 区分终端与server
RCST_MODE=1
# SYSTEM_TYPE="TD"
SYSTEM_TYPE="linux"

TABLENAME_ARRAY="nat mangle"

# 隧道协议端口定义
TUNNEL_USE_PORT=8000
# 代理监听端口（rediret重定向到此端口）
PROXY_LISTEN_PORT=9000

# 白名单规则通配符定义（需要与网管协商达成一致）
IP_Wildcard="0.0.0.0"
PORT_Wildcard="0"

# 日志文件名称
LOG_NAME="white_list"
IPTABLES="iptables"
if [ $RCST_MODE = "1" ]; then
  # 终端区分TD系统与linux系统
  if [ $SYSTEM_TYPE = "linux" ]; then
    ROOT_PERMISSION="$sudo"
    IPTABLES="iptables"
    HANDLE_LOG_PATH="bash/handle_tcp_log.sh"
  else
    # 日志处理脚本文件路径
    HANDLE_LOG_PATH="/bin/script/handle_tcp_log.sh"
  fi
else
  IPTABLES="iptables-nft"
fi


# 将IP字符串转为十六进制值（带0x前缀）
ipstr2hex() {
  local ip=$1
  local num=$(echo $ip | awk -F. '{printf("%x%02x%02x%02x", $4,$3,$2,$1)}')
  echo "0x$num"
}

# 准备过滤规则
ready_filtration_rule() {
  local src_ip=$1
  local src_port=$2
  local dst_ip=$3
  local dst_port=$4
  # 过滤细则
  local filtration_rule=" -p tcp "
  # 增加白名单规则（前端保障规则不重复）
  if [ "$src_ip" != "$IP_Wildcard" ]; then
    filtration_rule="$filtration_rule -s $src_ip "
  fi
  if [ "$src_port" != "$PORT_Wildcard" ]; then
    filtration_rule="$filtration_rule --sport $src_port "
  fi
  if [ "$dst_ip" != "$IP_Wildcard" ]; then
    filtration_rule="$filtration_rule -d $dst_ip "
  fi
  if [ "$dst_port" != "$PORT_Wildcard" ]; then
    filtration_rule="$filtration_rule --dport $dst_port "
  fi
  echo $filtration_rule
}

# 操作PREROUTING中的规则
opt_preroouting_rule() {
  local tablename=$1
  local opt=$2
  local vrf_id=$3
  local rcst_ip_str=$4

  # 添加/删除 从指定vlan来的tcp建链包（ "! --dport 8000 " 端口8000是隧道的协议端口，不能抓）
  $ROOT_PERMISSION $IPTABLES -t $tablename $opt PREROUTING -i vlan$vrf_id -p tcp ! --dport $TUNNEL_USE_PORT --syn -j TCP_${rcst_ip_str}_${vrf_id} -w | ($HANDLE_LOG_PATH $LOG_NAME)
  if [ $? -ne 0 ]; then
    echo "$ROOT_PERMISSION $IPTABLES -t $tablename $opt PREROUTING -i vlan$vrf_id -p tcp ! --dport $TUNNEL_USE_PORT --syn -j TCP_${rcst_ip_str}_${vrf_id} -w " | ($HANDLE_LOG_PATH $LOG_NAME)
    return 1
  fi

  return 0
}

# 操作POSTROUTING中的规则
opt_postrouting_rule() {
  local tablename=$1
  local opt=$2
  local vrf_id=$3
  local rcst_ip_str=$4
  local chain_name="TCP_NAT_${rcst_ip_str}_${vrf_id}"

  # 添加/删除 从 POSTROUTING 链中 匹配到 指定小站+VRF需要操作SNAT的链中
  local opt_postrouting_cmd="$ROOT_PERMISSION $IPTABLES -t $tablename $opt -o vlan$vrf_id POSTROUTING -p tcp -j $chain_name -w"
  eval $opt_postrouting_cmd
  if [ $? -ne 0 ]; then
    echo "run cmd: [ $opt_postrouting_cmd ] failed" | ($HANDLE_LOG_PATH $LOG_NAME)
    return 1
  fi

  return 0
}

# 清除TCP加速_规则链
clear_tcp_faster_chain() {
  local tablename=$1
  local vrf_id=$2
  local rcst_ip_str=$3
  local chain_name="TCP_${rcst_ip_str}_${vrf_id}"

  # 链存在才操作
  $ROOT_PERMISSION $IPTABLES -t $tablename -nL -w | grep "Chain $chain_name" > /dev/null 
  if [ $? -ne 0 ]; then
    return 0
  fi

  # 删除PREROUTING链中的跳转到TCP_$rcst_ip_$vrf_id链的规则
  opt_preroouting_rule $tablename "-D" $vrf_id $rcst_ip_str
  
  # 当nat/mangle表中的TCP_$rcst_ip_$vrf_id链下没有规则时，将TCP_$rcst_ip_$vrf_id链删
  local nat_rule_num=`$ROOT_PERMISSION $IPTABLES -t $tablename -nL $chain_name -w | wc -l`
  if [ $nat_rule_num -eq 2 ]; then
    $ROOT_PERMISSION $IPTABLES -t $tablename -X $chain_name -w
  fi
  return 0
}

new_tcp_faster_chain() {
  local tablename=$1
  local rcst_ip_str=$2
  local vrf_id=$3
  # 根据小站地址和vrf_id创建iptables规则链
  $ROOT_PERMISSION $IPTABLES -t $tablename -nL -w | grep "Chain TCP_${rcst_ip_str}_${vrf_id}" > /dev/null 
  if [ $? -ne 0 ]; then
    # nat/mangle表中没有找到，创建nat/mangle表中的TCP_$rcst_ip_$vrf_id链
    $ROOT_PERMISSION $IPTABLES -t $tablename -N TCP_${rcst_ip_str}_${vrf_id} -w | ($HANDLE_LOG_PATH $LOG_NAME)
    if [ $? -ne 0 ]; then
      # nat/mangle表中的链创建失败
      echo "$ROOT_PERMISSION $IPTABLES -t $tablename -N TCP_${rcst_ip_str}_${vrf_id} -w" | ($HANDLE_LOG_PATH $LOG_NAME)
      return 1
    fi
  fi
}

# 根据小站地址和vrf_id创建iptable nat规则链
new_tcp_faster_nat_chain() {
  local rcst_ip_str=$1
  local vrf_id=$2
  local chain_name="TCP_NAT_${rcst_ip_str}_${vrf_id}"
  local tablename="nat"

  $ROOT_PERMISSION $IPTABLES -t $tablename -nL -w | grep "Chain $chain_name" > /dev/null 
  if [ $? -ne 0 ]; then
    # nat表中没有找到，创建nat表中的TCP_NAT_$rcst_ip_$vrf_id链
    local new_nat_chain="$ROOT_PERMISSION $IPTABLES -t $tablename -N $chain_name -w"
    eval $new_nat_chain
    if [ $? -ne 0 ]; then
      # 链创建失败
      echo "run cmd: [ $new_nat_chain ] failed" | ($HANDLE_LOG_PATH $LOG_NAME)
      return 1
    fi
  fi
}

# 添加白名单规则  ./white_list.sh add vrf4 10.0.32.3:0-10.0.30.111:5201-RCST_IP
add_white_list() {
  local vrf_id=`echo $1 | awk -F'vrf' '{print $2}'`
  local s_addr=$2
  local d_addr=$3
  local rcst_ip=$4

  local sip=$(echo $s_addr | cut -d: -f1)
  local sport=$(echo $s_addr | cut -d: -f2)
  local dip=$(echo $d_addr | cut -d: -f1)
  local dport=$(echo $d_addr | cut -d: -f2)

  # 根据小站地址和vrf_id创建iptables规则链
  new_tcp_faster_chain "nat" $rcst_ip $vrf_id
  if [ $? -ne 0 ]; then
      return 1
  fi
  new_tcp_faster_chain "mangle" $rcst_ip $vrf_id
  if [ $? -ne 0 ]; then
      return 1
  fi

  # 过滤细则
  local filtration_rule=$(ready_filtration_rule $sip $sport $dip $dport)
  
  if [ $rcst_ip = "FASTER" ]; then
    # 添加白名单规则到iptables规则链
    $ROOT_PERMISSION $IPTABLES -t nat -A TCP_${rcst_ip}_${vrf_id} $filtration_rule -j REDIRECT_PEP --to-port=$PROXY_LISTEN_PORT -w | ($HANDLE_LOG_PATH $LOG_NAME)
    if [ $? -ne 0 ]; then
      echo "$ROOT_PERMISSION $IPTABLES -t nat -A TCP_${rcst_ip}_${vrf_id} $filtration_rule -j REDIRECT_PEP --to-port=$PROXY_LISTEN_PORT -w" | ($HANDLE_LOG_PATH $LOG_NAME)
      return 1
    fi

    # 添加白名单规则到mangle表中
    $ROOT_PERMISSION $IPTABLES -t mangle -A TCP_${rcst_ip}_${vrf_id} $filtration_rule  -j NFQUEUE_PEP --queue-num=$vrf_id -w | ($HANDLE_LOG_PATH $LOG_NAME)
    if [ $? -ne 0 ]; then
      echo "$ROOT_PERMISSION $IPTABLES -t mangle -A TCP_${rcst_ip}_${vrf_id} $filtration_rule  -j NFQUEUE_PEP --queue-num=$vrf_id -w" | ($HANDLE_LOG_PATH $LOG_NAME)
      return 1
    fi

  else
    # 将小站IP字符串转为数值
    local rcst_ip_num=$(ipstr2hex $rcst_ip)
    
    # 添加白名单规则到iptables规则链（nat表中，当只有小站地址不同，其他参数相同时，会被重复添加）
    $ROOT_PERMISSION $IPTABLES -t nat -A TCP_${rcst_ip}_${vrf_id} $filtration_rule -j REDIRECT_PEP --to-port=$PROXY_LISTEN_PORT -w | ($HANDLE_LOG_PATH $LOG_NAME)
    if [ $? -ne 0 ]; then
      echo "$ROOT_PERMISSION $IPTABLES -t nat -A TCP_${rcst_ip}_${vrf_id} $filtration_rule -j REDIRECT_PEP --to-port=$PROXY_LISTEN_PORT -w" | ($HANDLE_LOG_PATH $LOG_NAME)
      return 1
    fi

    # 添加白名单规则到mangle表中（设置mark标记，用于匹配后续的nfqueue规则）
    $ROOT_PERMISSION $IPTABLES -t mangle -I TCP_${rcst_ip}_${vrf_id} $filtration_rule  -j MARK --set-mark $rcst_ip_num -w | ($HANDLE_LOG_PATH $LOG_NAME)
    if [ $? -ne 0 ]; then
      echo "$ROOT_PERMISSION $IPTABLES -t mangle -I TCP_${rcst_ip}_${vrf_id} $filtration_rule  -j MARK --set-mark $rcst_ip_num -w" | ($HANDLE_LOG_PATH $LOG_NAME)
      return 1
    fi

    # 匹配mark丢到nfqueue_pep队列，每个mark匹配只需要一条规则，不重复添加
    $ROOT_PERMISSION $IPTABLES -t mangle -nvL TCP_${rcst_ip}_${vrf_id} -w | grep "mark match $rcst_ip_num NFQUEUE num $vrf_id" > /dev/null
    if [ $? -ne 0 ]; then
      $ROOT_PERMISSION $IPTABLES -t mangle -A TCP_${rcst_ip}_${vrf_id} -m mark --mark $rcst_ip_num -j NFQUEUE_PEP --queue-num=$vrf_id -w | ($HANDLE_LOG_PATH $LOG_NAME)
      if [ $? -ne 0 ]; then
        echo "$ROOT_PERMISSION $IPTABLES -t mangle -A TCP_${rcst_ip}_${vrf_id} -m mark --mark $rcst_ip_num -j NFQUEUE_PEP --queue-num=$vrf_id -w" | ($HANDLE_LOG_PATH $LOG_NAME)
        return 1
      fi
    fi
  fi
  
  return 0
}

# 删除单条白名单规则  ./white_list.sh del vrf4 10.0.32.3:0-10.0.30.111:5201-RCST_IP
delete_white_list_one() {
  local vrf_id=`echo $1 | awk -F'vrf' '{print $2}'`
  local s_addr=$2
  local d_addr=$3
  local rcst_ip=$4

  local sip=$(echo $s_addr | cut -d: -f1)
  local sport=$(echo $s_addr | cut -d: -f2)
  local dip=$(echo $d_addr | cut -d: -f1)
  local dport=$(echo $d_addr | cut -d: -f2)

  # 过滤细则
  local filtration_rule=$(ready_filtration_rule $sip $sport $dip $dport)

  if [ $rcst_ip = "FASTER" ]; then

    # 删除mangle表中的白名单规则
    $ROOT_PERMISSION $IPTABLES -t mangle -D TCP_FASTER_$vrf_id $filtration_rule -j NFQUEUE_PEP --queue-num=$vrf_id -w | ($HANDLE_LOG_PATH $LOG_NAME)
    if [ $? -ne 0 ]; then
      echo "$ROOT_PERMISSION $IPTABLES -t mangle -D TCP_FASTER_$vrf_id $filtration_rule -j NFQUEUE_PEP --queue-num=$vrf_id -w " | ($HANDLE_LOG_PATH $LOG_NAME)
      return 1
    fi

    # 删除nat表中的白名单规则
    $ROOT_PERMISSION $IPTABLES -t nat -D TCP_FASTER_$vrf_id $filtration_rule -j REDIRECT_PEP --to-port=$PROXY_LISTEN_PORT -w | ($HANDLE_LOG_PATH $LOG_NAME)
    if [ $? -ne 0 ]; then
      echo "$ROOT_PERMISSION $IPTABLES -t nat -D TCP_FASTER_$vrf_id $filtration_rule -j REDIRECT_PEP --to-port=$PROXY_LISTEN_PORT -w " | ($HANDLE_LOG_PATH $LOG_NAME)
      return 1
    fi

  else
    # 将小站IP字符串转为数值
    local rcst_ip_num=$(ipstr2hex $rcst_ip)

    # 删除mangle表中的白名单规则
    $ROOT_PERMISSION $IPTABLES -t mangle -D TCP_${rcst_ip}_${vrf_id} $filtration_rule -j MARK --set-mark $rcst_ip_num -w | ($HANDLE_LOG_PATH $LOG_NAME)
    if [ $? -ne 0 ]; then
      echo "$ROOT_PERMISSION $IPTABLES -t mangle -D TCP_${rcst_ip}_${vrf_id} $filtration_rule -j MARK --set-mark $rcst_ip_num -w " | ($HANDLE_LOG_PATH $LOG_NAME)
      return 1
    fi
    # 当mark设置的规则清除完之后，删除mark匹配的规则
    local set_mark_num=`$ROOT_PERMISSION $IPTABLES -t mangle -nL TCP_${rcst_ip}_${vrf_id} -w | grep -w "MARK set $rcst_ip_num" | wc -l`
    if [ $set_mark_num -eq 0 ]; then
      $ROOT_PERMISSION $IPTABLES -t mangle -D TCP_${rcst_ip}_${vrf_id} -m mark --mark $rcst_ip_num -j NFQUEUE_PEP --queue-num=$vrf_id -w | ($HANDLE_LOG_PATH $LOG_NAME)
      if [ $? -ne 0 ]; then
        echo "$ROOT_PERMISSION $IPTABLES -t mangle -D TCP_${rcst_ip}_${vrf_id} -m mark --mark $rcst_ip_num -j NFQUEUE_PEP --queue-num=$vrf_id -w " | ($HANDLE_LOG_PATH $LOG_NAME)
        return 1
      fi
    fi

    # 删除nat表中的白名单规则
    $ROOT_PERMISSION $IPTABLES -t nat -D TCP_${rcst_ip}_${vrf_id} $filtration_rule -j REDIRECT_PEP --to-port=$PROXY_LISTEN_PORT -w | ($HANDLE_LOG_PATH $LOG_NAME)
    if [ $? -ne 0 ]; then
      echo "$ROOT_PERMISSION $IPTABLES -t nat -D TCP_${rcst_ip}_${vrf_id} $filtration_rule -j REDIRECT_PEP --to-port=$PROXY_LISTEN_PORT -w " | ($HANDLE_LOG_PATH $LOG_NAME)
      return 1
    fi

  fi

  return 0
}

delete_white_list_vrf_all() {
  local vrf_id=`echo $1 | awk -F'vrf' '{print $2}'`
  
  vrf_array=$($ROOT_PERMISSION $IPTABLES -t mangle -nL -w | grep "Chain TCP_.*_$vrf_id" | awk -F' ' '{print $2}')
  for tablename in $TABLENAME_ARRAY; do
    for chain_name in "$vrf_array"; do
      $ROOT_PERMISSION $IPTABLES -t $tablename -F $chain_name -w
      # local rcst_ip_str=$(echo $chain_name | awk -F'_' '{print $2}')
      # opt_preroouting_rule $tablename "-D" $vrf_id $rcst_ip_str
      $ROOT_PERMISSION $IPTABLES -t $tablename -X $chain_name -w
    done
  done

  return 0
}

delete_white_list_rcst_all() {
  local rcst_ip_str=$1
  
  vrf_array=$($ROOT_PERMISSION $IPTABLES -t mangle -nL -w | grep "Chain TCP_${rcst_ip_str}_*" | awk -F' ' '{print $2}')
  for tablename in $TABLENAME_ARRAY; do
    for chain_name in "$vrf_array"; do
      $ROOT_PERMISSION $IPTABLES -t $tablename -F $chain_name -w
      # local vrf_id=$(echo $chain_name | awk -F'_' '{print $3}')
      # opt_preroouting_rule $tablename "-D" $vrf_id $rcst_ip_str
      $ROOT_PERMISSION $IPTABLES -t $tablename -X $chain_name -w
    done
  done

  return 0
}

delete_white_list_rcst_vrf() {
  local rcst_ip_str=$1
  local vrf_id=`echo $2 | awk -F'vrf' '{print $2}'`
  
  chain_name="TCP_${rcst_ip_str}_${vrf_id}"
  for tablename in $TABLENAME_ARRAY; do
    $ROOT_PERMISSION $IPTABLES -t $tablename -F $chain_name -w
    # opt_preroouting_rule $tablename "-D" $vrf_id $rcst_ip_str
    $ROOT_PERMISSION $IPTABLES -t $tablename -X $chain_name -w
  done

  return 0
}

clear_tcp_faster_nat_chain_from_chainname() {
  local chain_name=$1
  local dev_name="vlan$2"
  # 删除nat表中POSTROUTING链中跳转到的TCP_NAT_$rcst_ip_$vrf_id的规则
  $ROOT_PERMISSION $IPTABLES -t nat -D POSTROUTING -o $dev_name vlan -p tcp -j $chain_name -w
  # 当tunnel断开时，删除nat表中的TCP_NAT_$rcst_ip_$vrf_id链
  $ROOT_PERMISSION $IPTABLES -t "nat" -F $chain_name -w
  $ROOT_PERMISSION $IPTABLES -t "nat" -X $chain_name -w
}

enable_white_list() {
  local rcst_ip_str=$1
  local vrf_id=`echo $2 | awk -F'vrf' '{print $2}'`

  if [ $RCST_MODE = "1" ] && [ $rcst_ip_str = "0.0.0.0" ]; then
    rcst_ip_str="FASTER"
  fi

  # 新建TCP_${rcst_ip}_${vrf_id}链
  new_tcp_faster_chain "nat" $rcst_ip_str $vrf_id
  if [ $? -ne 0 ]; then
    ret=1
  fi
  $ROOT_PERMISSION $IPTABLES -t nat -nvL PREROUTING -w | grep "TCP_${rcst_ip_str}_${vrf_id}" > /dev/null
  if [ $? -ne 0 ]; then
    opt_preroouting_rule "nat" "-A" $vrf_id $rcst_ip_str
    if [ $? -ne 0 ]; then
      return 1
    fi
  fi
  
  new_tcp_faster_chain "mangle" $rcst_ip_str $vrf_id
  if [ $? -ne 0 ]; then
    ret=1
  fi  
  $ROOT_PERMISSION $IPTABLES -t mangle -nvL PREROUTING -w | grep "TCP_${rcst_ip_str}_${vrf_id}" > /dev/null
  if [ $? -ne 0 ]; then
    opt_preroouting_rule "mangle" "-A" $vrf_id $rcst_ip_str
    if [ $? -ne 0 ]; then
      return 1
    fi
  fi
}

enable_snat() {
  local rcst_ip_str=$1
  local vrf_id=`echo $2 | awk -F'vrf' '{print $2}'`
  
  # 新建TCP_NAT_${rcst_ip}_${vrf_id}链 TCP_NAT_%s_%u
  new_tcp_faster_nat_chain $rcst_ip_str $vrf_id
  if [ $? -ne 0 ]; then
    return 1
  fi
  opt_postrouting_rule "nat" "-A" $vrf_id $rcst_ip_str
  if [ $? -ne 0 ]; then
    return 1
  fi
}


disable_white_list() {
  local rcst_ip_str_array=$1
  local vrf_id_array=`echo $2 | awk -F'vrf' '{print $2}'`

  if [ $RCST_MODE = "1" ] && [ $rcst_ip_str = "0.0.0.0" ]; then
    rcst_ip_str="FASTER"
  fi

  # 全部清理
  if [ $1 = "0.0.0.0" ] && [ $2 = "all" ]; then
    chain_array=$($ROOT_PERMISSION $IPTABLES -t nat -nL PREROUTING -w | grep "TCP_.*" | awk '{print $1}')
    for tablename in $TABLENAME_ARRAY; do
      for chain in $chain_array; do
        vrf_id=$(echo $chain | awk -F'_' '{print $3}')
        rcst_ip_str=$(echo $chain | awk -F'_' '{print $2}')
        clear_tcp_faster_chain $tablename $vrf_id $rcst_ip_str
      done
    done
  else
    # 清除指定vrf
    if [ $1 = "0.0.0.0" ]; then
      rcst_ip_str_array=$($ROOT_PERMISSION $IPTABLES -t nat -nL PREROUTING -w | grep "TCP_.*_${vrf_id_array}" | awk '{print $1}' | awk -F'_' '{print $2}')
    fi

    # 清除指定小站
    if [ $2 = "all" ]; then
      vrf_id_array=$($ROOT_PERMISSION $IPTABLES -t nat -nL PREROUTING -w | grep "TCP_${rcst_ip_str_array}_*" | awk '{print $1}' | awk -F'_' '{print $3}')
    fi
  fi

  # echo "disable white list: $rcst_ip_str_array $vrf_id_array"
  for tablename in $TABLENAME_ARRAY; do
    for rcst_ip_str in $rcst_ip_str_array; do
      for vrf_id in $vrf_id_array; do
        clear_tcp_faster_chain $tablename $vrf_id $rcst_ip_str
        if [ $? -ne 0 ]; then
          return 1
        fi
      done
    done
  done

}

disable_snat() {
  # rcst_ip_str 可能为具体IP 或者 全选 0.0.0.0
  local rcst_ip_str=$1
  # $2可能是 vrfname(如vrf4) 或 "all"；
  # 当为"vrfname"时vrf_id_array为当前vrf的id；当为"all"时，vrf_id_array会在后续使用，并赋值为当前所有vrf的id
  local vrf_name=$2

  vrf_id=""
  # 全部清理
  if [ $rcst_ip_str = "0.0.0.0" ] && [ $vrf_name = "all" ]; then
    rcst_ip_str=".*"
    vrf_id=".*"
  else
    # 清除指定vrf下的所有小站
    if [ $rcst_ip_str = "0.0.0.0" ]; then
      vrf_id=`echo $vrf_name | awk -F'vrf' '{print $2}'`
      rcst_ip_str=".*"
    # 清除指定小站中的所有vrf
    elif [ $vrf_name = "all" ]; then
      vrf_id=".*"
    else
      vrf_id=`echo $vrf_name | awk -F'vrf' '{print $2}'`
    fi
  fi
  grep_str="TCP_NAT_${rcst_ip_str}_${vrf_id}"
  chain_array=$($ROOT_PERMISSION $IPTABLES -t nat -nL POSTROUTING -w | grep $grep_str | awk '{print $1}')
  for chain in $chain_array; do
    vrf_id=$(echo $chain | awk -F'_' '{print $4}')
    clear_tcp_faster_nat_chain_from_chainname $chain $vrf_id
  done

}

# =================================================================================
# ===                                                                           ===
# ===                                  脚本入口                                  ===
# ===                                                                           ===
# =================================================================================
ret=0
if [ $# -lt 1 ]; then
  echo "failed"
  echo "err! Usage: $0 [add/del/enable/disable]"
  exit 1
fi

# 保存当前$IPTABLES配置
$ROOT_PERMISSION $IPTABLES-save > $IPTABLES.rules.bak | ($HANDLE_LOG_PATH $LOG_NAME)

# 安装redirect_pep_global模块
module_name="redirect_pep_global"
lsmod | grep $module_name > /dev/null
if [ $? -ne 0 ]; then
  $ROOT_PERMISSION iptables -t nat -nL -w > /dev/null
  $ROOT_PERMISSION iptables -t mangle -nL -w > /dev/null
  module_path=$(find /lib/modules/ -name $module_name.ko)
  if [ "$module_path" ]; then
    insmod $module_path
    if [ $? -ne 0 ]; then
      echo "insmod $module_name.ko fail. Please manually compile and install."
      exit 1
    fi
  else 
    echo "not find $module_name.ko."
  fi
fi

if [ "$1" = "add" ]; then
  if [ $# -lt 3 ]; then
    echo "failed"
    echo "err! Usage: $0 add [vrfname/cfg_file] <src_ip:sport1-dst_ip:dport1-rcst_ip>/file_path"
    echo "example: $0 add vrf4 10.0.32.3:0-10.0.30.111:5201-10.0.31.11"
    echo "     or: $0 add cfg_file config/rcstip_vrfname"
    exit 1
  fi
  if [ $2 = "cfg_file" ]; then
    # 解析配置文件，并调用add函数
    vrfname=`echo $3 | awk -F'_' '{print $2}'`
    for line in $(cat $3); do
      if [ -z "$line" ]; then
        continue
      fi
      s_addr=$(echo "$line" | cut -d'-' -f1)
      d_addr=$(echo "$line" | cut -d'-' -f2)
      rcst_ip=$(echo "$line" | cut -d'-' -f3)
      # echo "add vrf[$vrfname]  src_ip[$s_addr] dst_ip[$d_addr] rcst_ip[$rcst_ip]"
      add_white_list $vrfname $s_addr $d_addr $rcst_ip
      if [ $? -ne 0 ]; then
        ret=1
        break
      fi
    done
  else   
    vrfname=$2
    # 一个vrf下支持一次添加多条规则，多条规则间使用' '分割
    shift 2 # 移除前面2个参数，从第三个参数开始循环
    for arg do
      # 解析参数并调用 add 函数
      s_addr=$(echo "$arg" | cut -d'-' -f1)
      d_addr=$(echo "$arg" | cut -d'-' -f2)
      rcst_ip=$(echo "$arg" | cut -d'-' -f3)
      add_white_list $vrfname $s_addr $d_addr $rcst_ip
      if [ $? -ne 0 ]; then
        ret=1
        break
      fi
    done
  fi
elif [ $1 = "del" ]; then

  if [ $# -lt 4 ]; then
    echo "failed"
    echo "err! Usage: $0 del [vrf] vrfname all/one(<src_ip:sport1-dst_ip:dport1-rcst_ip>)"
    echo "example: $0 del vrf vrf4 10.0.32.3:0-10.0.30.111:5201-10.0.31.11"
    echo "     or: $0 del vrf vrf4 all"
    echo "     Usage: $0 del [rcst] ip_str all/group(<vrfname>)"
    echo "example: $0 del rcst 10.0.31.11 vrf4"
    echo "     or: $0 del rcst 10.0.31.11 all"
    exit 1
  fi
  # 以vrf为单位删除白名单规则
  if [ $2 = "vrf" ]; then
    vrfname=$3
    if [ $4 = "all" ]; then
      delete_white_list_vrf_all $vrfname
      if [ $? -ne 0 ]; then
        ret=1
      fi
    else
      # 一个vrf下支持一次删除多条规则，多条规则间使用' '分割
      shift 3 # 移除前面3个参数，从第4个参数开始循环
      for arg do
        # 解析参数并调用 delete 函数
        s_addr=$(echo "$arg" | cut -d'-' -f1)
        d_addr=$(echo "$arg" | cut -d'-' -f2)
        rcst_ip=$(echo "$arg" | cut -d'-' -f3)
        delete_white_list_one $vrfname $s_addr $d_addr $rcst_ip
        if [ $? -ne 0 ]; then
          ret=1
          break
        fi
      done
    fi
  # 以小站IP为单位删除白名单规则
  elif [ $2 = "rcst" ]; then
    if [ $4 = "all" ]; then
      delete_white_list_rcst_all $3
      if [ $? -ne 0 ]; then
        ret=1
      fi
    else
      delete_white_list_rcst_vrf $3 $4
      if [ $? -ne 0 ]; then
        ret=1
      fi
    fi
  else 
    echo "failed"
    echo "err! Usage: $0 del [vrf/rcst]"
  fi
elif [ $1 = "enable" ]; then
  if [ $# -lt 3 ]; then
    echo "failed"
    echo "err! Usage: $0 enable rcst_ip_str vrfname"
    echo "example: $0 enable 10.0.31.11 vrf4"
    exit 1
  fi
  rcst_ip_str=$2
  vrfname=$3
  # vrf_id=`echo $vrfname | awk -F'vrf' '{print $2}'`
  # 启用白名单
  enable_white_list $rcst_ip_str $vrfname
  if [ $? -ne 0 ]; then
    ret=1
  fi
elif [ $1 = "disable" ]; then
  if [ $# -lt 3 ]; then
    echo "failed"
    echo "err! Usage: $0 disable rcst_ip_str vrfname"
    echo "example: $0 disable 10.0.31.11 vrf4"
    exit 1
  fi
  rcst_ip_str=$2
  vrfname=$3
  # 禁用白名单
  disable_white_list $rcst_ip_str $vrfname
  if [ $? -ne 0 ]; then
    ret=1
  fi
elif [ $1 = "enable_nat" ]; then
  if [ $# -lt 3 ]; then
    echo "failed"
    echo "err! Usage: $0 $1 rcst_ip_str vrfname"
    echo "example: $0 $1 10.0.31.11 vrf4"
    exit 1
  fi
  rcst_ip_str=$2
  vrfname=$3
  enable_snat $rcst_ip_str $vrfname
  if [ $? -ne 0 ]; then
    ret=1
  fi
elif [ $1 = "disable_nat" ]; then
  if [ $# -lt 3 ]; then
    echo "failed"
    echo "err! Usage: $0 $1 rcst_ip_str(0.0.0.0 for all) vrfname(or all)"
    echo "example: $0 $1 10.0.31.11 vrf4"
    echo "del rcst: $0 $1 10.0.31.11 all"
    echo "del vrfx: $0 $1 0.0.0.0 vrf4"
    echo "del all: $0 $1 0.0.0.0 all"
    exit 1
  fi
  rcst_ip_str=$2
  vrfname=$3
  disable_snat $rcst_ip_str $vrfname
  if [ $? -ne 0 ]; then
    ret=1
  fi
else
  echo "failed"
  echo "err! Usage: $0 [add/del/enable/disable/enable_nat/disable_nat]"
  exit 1
fi

if [ $ret -ne 0 ]; then
  # 回滚$IPTABLES配置
  $ROOT_PERMISSION $IPTABLES-restore < $IPTABLES.rules.bak
  rm -f $IPTABLES.rules.bak
  echo "failed"
  exit 1
fi

# 成功，删除备份文件
rm -f $IPTABLES.rules.bak
echo "success"
exit 0